package bigapps.myneighbor.controller;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.csv.CSVParser;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.datastore.Blob;

import bigapps.myneighbor.dao.ParkingFacilityDao;
import bigapps.myneighbor.dao.StageDao;
import bigapps.myneighbor.domain.ParkingFacility;
import bigapps.myneighbor.domain.ParkingInfo;
import bigapps.myneighbor.domain.Stage;
import bigapps.myneighbor.service.ParkingFacilityService;
import bigapps.myneighbor.util.LatitudeLongitudeUtil;

@Controller
@RequestMapping(value = "/parking_facility")
public class ParkingFacilityController {
	private static final long serialVersionUID = 8305367618713715640L;
	@Autowired
	private ParkingFacilityService parkingFacilityService;

	@Autowired
	private StageDao stageDao;

	private static final Logger log = Logger
	.getLogger(ParkingFacilityController.class.getName());

	@RequestMapping(value = "/load_file", method = RequestMethod.POST)
	protected void loadFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		System.out.println("doPost");
		try {
			System.out.println("before isMultipart");
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);

			if (isMultipart) {
				System.out.println("isMultipart - true");
				ServletFileUpload servletFileUpload = new ServletFileUpload();
				FileItemIterator iter = servletFileUpload
				.getItemIterator(request);
				System.out.println("before while loop");

				byte b[] = new byte[100000];
				while (iter.hasNext()) {
					FileItemStream item = iter.next();
					String name = item.getFieldName();
					InputStream stream = item.openStream();
					int totalBytes = 0;
					int numBytes = 0;
					ByteArrayOutputStream aos = new ByteArrayOutputStream();
					while (!((numBytes = stream.read(b)) == -1)) {
						aos.write(b, 0, numBytes);
						totalBytes += numBytes;
					}
					System.out.println("total bytes: " + totalBytes);
					Blob blob = new Blob(aos.toByteArray());
					stageDao.saveParkingFacility(name, blob);
					/*
					 * if (item.isFormField()) {
					 * System.out.println("Form field " + name + " with value "
					 * + Streams.asString(stream) + " detected."); } else {
					 * System.out.println("File field " + name +
					 * " with file name " + item.getName() + " detected."); }
					 * BufferedReader reader = new BufferedReader(new
					 * InputStreamReader(stream)); CSVParser parser = new
					 * CSVParser(reader); String line[] = null; if((line =
					 * parser.getLine()) != null){ while((line =
					 * parser.getLine()) != null) { for(int i=1; i <
					 * line.length; i++){ System.out.println(line[i]); } try{
					 * parkingFacilityService.create(line); } catch(Exception e)
					 * { System.out.println(line[1] +
					 * " failed to get latitude and longitude");
					 * e.printStackTrace(); } } reader.close(); }
					 */
				}
			}
			out.println("Completed successfully!");
			out.flush();
		} catch (Exception e) {
			out.println("Failed!");
			out.flush();
			e.printStackTrace();
		}

		List<Stage> listStage = stageDao.findAll();
		for (Stage s : listStage) {
			System.out.println(s.getFileName());
			System.out.println(s.getType());
			System.out.println(new String(s.getContent().getBytes()));
		}
	}

	@RequestMapping(value = "/update_data", method = RequestMethod.GET)
	protected void updateData() throws IOException {
		System.out.println("ParkingFacilityController.updateData called");
		parkingFacilityService.updateData();
	}

	@RequestMapping(value = "/update_latitude_longitude", method = RequestMethod.GET)
	protected void update() throws IOException {
		parkingFacilityService.updateLatitudeLongitude();
	}

	@RequestMapping(value = "/repair_latitude_longitude", method = RequestMethod.GET)
	protected void repair() throws IOException {
		parkingFacilityService.repairLatitudeLongitude();
	}

	@RequestMapping(value = "/get_status", method = RequestMethod.GET)
	protected void getStatus(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String statusStr = parkingFacilityService.getStatus();
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println(statusStr);
		out.flush();
		out.close();
	}

	private FileItem getFileItem(HttpServletRequest request) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()
						&& "uploadFormElement".equals(item.getFieldName())) {
					return item;
				}
			}
		} catch (FileUploadException e) {
			return null;
		}
		return null;
	}
}
